# services/user_service.py
from contextlib import contextmanager

from app.database import SessionLocal
from app.models import User


class UserService:

    @contextmanager
    def session_scope(self):
        """事务管理上下文"""
        session = SessionLocal()
        try:
            yield session
            session.commit()
        except Exception:
            session.rollback()
            raise
        finally:
            session.close()

    def create_user(self, username: str, email: str) -> int:
        with self.session_scope() as session:
            # 检查唯一约束
            if session.query(User).filter(
                    (User.username == username) | (User.email == email)
            ).first():
                raise ValueError("用户名或邮箱已存在")

            new_user = User(username=username, email=email)
            session.add(new_user)
            session.flush()  # 立即获取ID
            return new_user.id

    def get_user(self, user_id: int) -> dict:
        """按ID查询用户（返回字典避免Detached状态）[11](@ref)"""
        with self.session_scope() as s:
            user = s.query(User).get(user_id)
            return {"id": user.id, "username": user.username} if user else None

    def get_all_user(self) -> dict:
        """按ID查询用户（返回字典避免Detached状态）[11](@ref)"""
        with self.session_scope() as s:
            user = s.query(User).all()
            return user if user else None

    def batch_create_users(self, user_list: list):
        """批量插入（性能优化）[11](@ref)"""
        with self.session_scope() as s:
            s.bulk_insert_mappings(  # 比循环add快10倍+
                User,
                [{"username": u[0], "email": u[1]} for u in user_list]
            )

    def search_users(self, keyword: str) -> list:
        """关键词搜索（防止SQL注入）[10](@ref)"""
        with self.session_scope() as s:
            return s.query(User).filter(
                User.username.ilike(f"%{keyword}%")  # 自动参数化
            ).all()
